package com.example.linuxweb.controller;

import com.example.linuxweb.model.Command;
import com.example.linuxweb.model.TerminalSession;
import com.example.linuxweb.service.CommandService;
import com.example.linuxweb.service.FileSystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class TerminalController {
    private final CommandService commandService;
    private final FileSystemService fileSystemService;

    @Autowired
    public TerminalController(CommandService commandService, FileSystemService fileSystemService) {
        this.commandService = commandService;
        this.fileSystemService = fileSystemService;
    }

    @GetMapping("/")
    public String terminal(HttpSession session, Model model) {
        String sessionId = session.getId();
        TerminalSession terminalSession = fileSystemService.getSession(sessionId);

        if (terminalSession == null) {
            terminalSession = fileSystemService.createNewSession();
            fileSystemService.getSessions().put(sessionId, terminalSession);
        }

        model.addAttribute("commandHistory", terminalSession.getCommandHistory());
        model.addAttribute("currentDirectory", terminalSession.getFileSystem().getCurrentDirectory().getPath());
        return "terminal";
    }

    @PostMapping("/execute")
    @ResponseBody
    public Command executeCommand(@RequestParam String command, HttpSession session) {
        String sessionId = session.getId();
        TerminalSession terminalSession = fileSystemService.getSession(sessionId);

        if (terminalSession == null) {
            terminalSession = fileSystemService.createNewSession();
            fileSystemService.getSessions().put(sessionId, terminalSession);
        }

        return commandService.executeCommand(command, terminalSession);
    }
}